package com.eims.sls_app.ui;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BitmapUtils;
import com.eims.sls_app.utils.ImageManager;
import com.eims.sls_app.utils.UploadUtil;
import com.eims.sls_app.view.MyToast;
import com.eims.sls_app.view.XCRoundImageView;

import bls.juejin.cn.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class PerfectdataActivity extends MyBaseActivity implements OnClickListener {
	private XCRoundImageView iv_icon;
	private RelativeLayout rl_icon,rl_choose_picture,rl_take_pictrue;
	private ImageButton btn_back;
	
	protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    private static final int AVATAR_PICTURE = 3;
	private static final String TAG = "PerfectdataActivity";
    protected static Uri tempUri;
    private ImageView iv_personal_icon;
    private Context context;
	private MyHandler mHandler;
	private String imagePath;
	private MyAsynTask myAsynTask;
	private String url;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_perfect_data);
		initView();
		ivitlist();
		ImageManager.getInstance().displayImage(
				App.user.getHeadUrl(), iv_icon,
				ImageManager.getViewsHeadOptions());
	}

	private void ivitlist() {
		//rl_icon.setOnClickListener(this);
		rl_choose_picture.setOnClickListener(this);
		rl_take_pictrue.setOnClickListener(this);
		btn_back.setOnClickListener(this);
	}

	private void initView() {
		mHandler = new MyHandler();
		iv_icon = (XCRoundImageView) findViewById(R.id.iv_icon_data);
		rl_icon = (RelativeLayout) findViewById(R.id.rl_icon_data);
		rl_choose_picture = (RelativeLayout) findViewById(R.id.rl_choose_picture);
		rl_take_pictrue = (RelativeLayout) findViewById(R.id.rl_take_pictrue);
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.rl_icon_data:
			Intent intent = new Intent(PerfectdataActivity.this,AvatarActivity.class);
			startActivityForResult(intent, AVATAR_PICTURE);
			
			break;
		case R.id.rl_choose_picture:
			Intent openAlbumIntent ;
			//openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
			//openAlbumIntent.setType("image/*");
			if (Build.VERSION.SDK_INT < 19) {
				openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
				openAlbumIntent.setType("image/*");
				} else {
					openAlbumIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

				}
			//openAlbumIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
			break;
		case R.id.rl_take_pictrue:
			Intent openCameraIntent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            tempUri = Uri.fromFile(new File(Environment
                    .getExternalStorageDirectory(), "image.jpg"));
            // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
           /* if (hasSdcard()) {
            	PhotoAFile = new File(Environment
            	.getExternalStorageDirectory(),
            	IMAGEa_FILE_NAME);
            	intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,
            	Uri.fromFile(PhotoAFile));
            	}*/
            startActivityForResult(openCameraIntent, TAKE_PICTURE);
			break;
			
		case R.id.btn_back:
			Intent intentResuls = getIntent();
			intentResuls.putExtra("url", "http://888.qcai888.cn"+url);
			setResult(1, intentResuls);
			finish();
			break;

		default:
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
            case TAKE_PICTURE:
                startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                break;
            case CHOOSE_PICTURE:
                startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                break;
            case CROP_SMALL_PICTURE:
                if (data != null) {
                    setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                }
                break;
            case AVATAR_PICTURE:
            	
            	break;
            }
        }
	}

	private void startPhotoZoom(Uri uri) {
		if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        tempUri = uri;
        //Intent intent = new Intent("android.intent.action.PICK");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
		
	}
	
	/**
     * 保存裁剪之后的图片数据
     * 
     * @param
     * 
     * @param -picdata
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            photo = BitmapUtils.toRoundBitmap(photo, tempUri); // 这个时候的图片已经被处理成圆形的了
            iv_icon.setImageBitmap(photo);
            uploadPic(photo);
        }
    }
    
    private void uploadPic(Bitmap bitmap) {
        // 上传至服务器
        // ... 可以在这里把Bitmap转换成file，然后得到file的url，做文件上传操作
        // 注意这里得到的图片已经是圆形图片了
        // bitmap是没有做个圆形处理的，但已经被裁剪了

        imagePath = BitmapUtils.savePhoto(bitmap, Environment
                .getExternalStorageDirectory().getAbsolutePath(), String
                .valueOf(System.currentTimeMillis()));
        Log.e("imagePath", imagePath+"");
        
        if(imagePath != null){
            myAsynTask = new MyAsynTask();
            myAsynTask.execute();
        }
    	/*File imageFile = BitmapUtils.saveFile(bitmap, Environment
                .getExternalStorageDirectory().getAbsolutePath(), String
                .valueOf(System.currentTimeMillis()));*/
    	

    }
    
    class MyAsynTask extends AsyncTask<Integer, Integer, String> {
		String error = "-1";

		@Override
		protected String doInBackground(Integer... params) {
			String key = MD5.md5(App.MD5_key);
			String time = RspBodyBaseBean.getTime();
			String info = "";
			
			String imei = RspBodyBaseBean.getIMEI(context);
			String crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
			String auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			String opt = "77";
			Map<String, String> map = new HashMap<String, String>();
			map.put("opt", opt);
			map.put("auth", auth);
			
			final Map<String, File> files = new HashMap<String, File>();
			files.put("info", new File(imagePath));
			try {
				final String request = UploadUtil.post(App.path, map, files);
				Log.i(TAG, "上传图片"+request);
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(request);
					error = jsonObject.optString("success");
					url = jsonObject.optString("url");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			
			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			mHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case 0:
				ImageManager.getInstance().displayImage(
						"http://888.qcai888.cn"+url, iv_icon,
						ImageManager.getViewsHeadOptions());
				break;
			case -1:
				MyToast.getToast(context, "上传超时").show();
				break;
			
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}

}
